package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RequestMapping("/admin/dish")
@RestController
@Api(tags = "菜品管理")
public class DishController {

    @Autowired
    DishService dishService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String CATEGORY_PREFIX = "category:";

    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO) {
        dishService.saveWithFlavor(dishDTO);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dto) {
        PageResult page = dishService.pageQuery(dto);
        return Result.success(page);
    }

    @DeleteMapping
    @ApiOperation("菜品删除")
    public Result delete( String ids) {
        dishService.deleteBatch(ids);
        cleanCache(CATEGORY_PREFIX + '*');
        return Result.success();
    }

    @GetMapping("{id}")
    @ApiOperation("根据id查询")
    public Result<DishVO> get(@PathVariable Long id){
        DishVO dishVO = dishService.getOne(id);
        return Result.success(dishVO);
    }

    @PutMapping
    @ApiOperation("更新菜品信息")
    public Result update(@RequestBody DishDTO dishDTO) {
        dishService.update(dishDTO);
        cleanCache(CATEGORY_PREFIX + '*');
        return Result.success();
    }

    @PostMapping("/status/{status}")
    @ApiOperation("修改菜品状态")
    public Result startOrStop(Long id,@PathVariable Integer status) {
        dishService.startOrStop(id,status);
        cleanCache(CATEGORY_PREFIX + '*');
        return Result.success();
    }

    private void cleanCache(String pattern) {
        //数据少就用keys了，数据量大的话用scan
        Set<String> keys = stringRedisTemplate.keys(pattern);
        if (keys != null) {
            stringRedisTemplate.delete(keys);
        }
    }
}
